import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import imaplib
import smtplib
import email
from email.header import decode_header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import json
import os
import re


# 2205080902048 mzh

# 1.设计邮件配置模块----------------------------------------------------------------------------------------------------
class MailConfig:

    def __init__(self, config_file='mail_config.json'):
        """初始化配置"""
        self.config_file = config_file
        self.smtp_server = ''
        self.smtp_port = 587
        self.imap_server = ''
        self.imap_port = 993
        self.pop3_server = ''
        self.pop3_port = 995
        self.email_address = ''
        self.password = ''
        self.use_ssl = True
        self.load_config()

    def load_config(self):
        """从文件加载配置"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r') as f:
                    config = json.load(f)
                    self.smtp_server = config.get('smtp_server', '')
                    self.smtp_port = config.get('smtp_port', 587)
                    self.imap_server = config.get('imap_server', '')
                    self.imap_port = config.get('imap_port', 993)
                    self.pop3_server = config.get('pop3_server', '')
                    self.pop3_port = config.get('pop3_port', 995)
                    self.email_address = config.get('email_address', '')
                    self.password = config.get('password', '')
                    self.use_ssl = config.get('use_ssl', True)
            except Exception as e:
                messagebox.showerror("配置错误", f"加载配置文件失败: {str(e)}")

    def save_config(self):
        """保存配置到文件"""
        config = {
            'smtp_server': self.smtp_server,
            'smtp_port': self.smtp_port,
            'imap_server': self.imap_server,
            'imap_port': self.imap_port,
            'pop3_server': self.pop3_server,
            'pop3_port': self.pop3_port,
            'email_address': self.email_address,
            'password': self.password,
            'use_ssl': self.use_ssl
        }
        try:
            with open(self.config_file, 'w') as f:
                json.dump(config, f, indent=4)
            return True
        except Exception as e:
            messagebox.showerror("配置错误", f"保存配置文件失败: {str(e)}")
            return False

    def get_smtp_server(self):
        return self.smtp_server

    def get_smtp_port(self):
        return self.smtp_port

    def get_imap_server(self):
        return self.imap_server

    def get_imap_port(self):
        return self.imap_port

    def get_pop3_server(self):
        return self.pop3_server

    def get_pop3_port(self):
        return self.pop3_port

    def get_email_address(self):
        return self.email_address

    def get_password(self):
        return self.password

    def get_use_ssl(self):
        return self.use_ssl

    def set_smtp_server(self, server):
        self.smtp_server = server

    def set_smtp_port(self, port):
        self.smtp_port = int(port)

    def set_imap_server(self, server):
        self.imap_server = server

    def set_imap_port(self, port):
        self.imap_port = int(port)

    def set_pop3_server(self, server):
        self.pop3_server = server

    def set_pop3_port(self, port):
        self.pop3_port = int(port)

    def set_email_address(self, email):
        self.email_address = email

    def set_password(self, password):
        self.password = password

    def set_use_ssl(self, use_ssl):
        self.use_ssl = bool(use_ssl)


# 邮件发送类，用于发送邮件
class MailSender:

    def __init__(self, config):
        """初始化邮件发送器"""
        self.config = config

    def connect(self):
        """连接SMTP服务器"""
        try:
            if self.config.use_ssl:
                server = smtplib.SMTP_SSL(self.config.smtp_server, self.config.smtp_port)
            else:
                server = smtplib.SMTP(self.config.smtp_server, self.config.smtp_port)
                server.starttls()  # 启用TLS加密

            server.login(self.config.email_address, self.config.password)
            return server
        except Exception as e:
            raise Exception(f"SMTP连接失败: {str(e)}")

    def build_message(self, to, subject, content, cc=None, bcc=None, html_content=None, attachments=None):
        """构建邮件消息"""
        msg = MIMEMultipart()
        msg['From'] = self.config.email_address
        msg['To'] = to
        msg['Subject'] = subject

        if cc:
            msg['Cc'] = cc

        # 添加纯文本内容
        if content:
            msg.attach(MIMEText(content, 'plain'))

        # 添加HTML内容
        if html_content:
            msg.attach(MIMEText(html_content, 'html'))

        # 添加附件
        if attachments:
            for file_path in attachments:
                try:
                    with open(file_path, 'rb') as attachment:
                        part = MIMEBase('application', 'octet-stream')
                        part.set_payload(attachment.read())
                    encoders.encode_base64(part)
                    part.add_header(
                        'Content-Disposition',
                        f'attachment; filename="{os.path.basename(file_path)}"'
                    )
                    msg.attach(part)
                except Exception as e:
                    raise Exception(f"添加附件失败: {str(e)}")

        return msg

    def send_email(self, to, subject, content, cc=None, bcc=None, html_content=None, attachments=None):
        """发送邮件"""
        try:
            # 构建邮件
            msg = self.build_message(to, subject, content, cc, bcc, html_content, attachments)

            # 连接服务器并发送
            server = self.connect()
            recipients = [to]
            if cc:
                recipients.extend(cc.split(','))
            if bcc:
                recipients.extend(bcc.split(','))

            server.sendmail(self.config.email_address, recipients, msg.as_string())
            server.quit()
            return True
        except Exception as e:
            raise Exception(f"发送邮件失败: {str(e)}")


# 邮件接收类，用于接收和处理邮件
class MailReceiver:

    def __init__(self, config):
        """初始化邮件接收器"""
        self.config = config

    def connect_imap(self):
        """连接IMAP服务器"""
        try:
            if self.config.use_ssl:
                server = imaplib.IMAP4_SSL(self.config.imap_server, self.config.imap_port)
            else:
                server = imaplib.IMAP4(self.config.imap_server, self.config.imap_port)

            server.login(self.config.email_address, self.config.password)
            return server
        except Exception as e:
            raise Exception(f"IMAP连接失败: {str(e)}")

    def fetch_emails(self, limit=20, search_criteria='ALL'):
        """获取邮件列表"""
        try:
            server = self.connect_imap()
            server.select('INBOX')

            # 搜索邮件
            status, messages = server.search(None, search_criteria)
            if status != 'OK':
                raise Exception("搜索邮件失败")

            # 获取邮件ID列表并反转，使最新的邮件在前
            messages = messages[0].split()
            messages = list(reversed(messages))

            # 限制获取的邮件数量
            messages = messages[:limit]

            emails = []
            for mail_id in messages:
                # 获取邮件头信息
                status, data = server.fetch(mail_id, '(BODY.PEEK[HEADER])')
                if status != 'OK':
                    continue

                # 解析邮件头
                msg = email.message_from_bytes(data[0][1])

                # 解码邮件主题
                subject, encoding = decode_header(msg["Subject"])[0] if msg["Subject"] else ("无主题", None)
                if isinstance(subject, bytes):
                    subject = subject.decode(encoding if encoding else 'utf-8')

                # 解码发件人信息
                from_, encoding = decode_header(msg.get("From"))[0] if msg.get("From") else ("未知发件人", None)
                if isinstance(from_, bytes):
                    from_ = from_.decode(encoding if encoding else 'utf-8')

                # 获取日期
                date = msg.get('Date', '未知日期')

                # 存储邮件信息
                emails.append({
                    'id': mail_id,
                    'subject': subject,
                    'from': from_,
                    'date': date,
                    'server': server  # 保存服务器连接
                })

            return emails
        except Exception as e:
            raise Exception(f"获取邮件列表失败: {str(e)}")

    def get_email_content(self, email_info):
        """获取邮件完整内容"""
        try:
            server = email_info['server']
            mail_id = email_info['id']

            status, data = server.fetch(mail_id, '(RFC822)')
            if status != 'OK':
                raise Exception("获取邮件内容失败")

            # 解析邮件
            msg = email.message_from_bytes(data[0][1])

            # 解析邮件内容
            content = {
                'from': email_info['from'],
                'date': email_info['date'],
                'subject': email_info['subject'],
                'text': '',
                'html': '',
                'attachments': []
            }

            if msg.is_multipart():  # 多部分邮件（可能包含附件）
                for part in msg.walk():
                    content_type = part.get_content_type()
                    content_disposition = str(part.get("Content-Disposition"))

                    try:
                        body = part.get_payload(decode=True).decode('utf-8')
                    except:
                        body = part.get_payload(decode=True)

                    # 纯文本内容
                    if content_type == "text/plain" and "attachment" not in content_disposition:
                        content['text'] += body
                    # HTML内容
                    elif content_type == "text/html" and "attachment" not in content_disposition:
                        content['html'] += body
                    # 附件
                    elif "attachment" in content_disposition:
                        filename = part.get_filename()
                        if filename:
                            content['attachments'].append({
                                'filename': filename,
                                'data': part.get_payload(decode=True)
                            })
            else:  # 单部分邮件
                content_type = msg.get_content_type()
                body = msg.get_payload(decode=True).decode('utf-8')
                if content_type == "text/plain":
                    content['text'] = body
                elif content_type == "text/html":
                    content['html'] = body

            return content
        except Exception as e:
            raise Exception(f"解析邮件内容失败: {str(e)}")

    def delete_email(self, email_info):
        """删除邮件"""
        try:
            server = email_info['server']
            mail_id = email_info['id']

            # 标记邮件为删除
            server.store(mail_id, '+FLAGS', '\\Deleted')
            server.expunge()  # 永久删除
            return True
        except Exception as e:
            raise Exception(f"删除邮件失败: {str(e)}")


# 邮件应用程序主界面
class EmailApp:

    def __init__(self, root):
        """初始化邮件应用程序"""
        self.root = root
        self.root.title("邮件收发程序")
        self.root.geometry("900x750")  # 设置窗口大小

        # 创建邮件配置
        self.config = MailConfig()

        # 创建邮件发送和接收对象
        self.mail_sender = MailSender(self.config)
        self.mail_receiver = MailReceiver(self.config)

        # 创建发送邮件相关的变量
        self.to_var = tk.StringVar()
        self.subject_var = tk.StringVar()
        self.content_var = tk.StringVar()
        self.cc_var = tk.StringVar()
        self.bcc_var = tk.StringVar()
        self.html_mode_var = tk.BooleanVar(value=False)
        self.attach_files = []

        # 创建接收邮件相关的变量
        self.search_criteria_var = tk.StringVar(value='ALL')
        self.limit_var = tk.IntVar(value=20)

        # 创建界面元素
        self.create_widgets()

        # 存储当前显示的邮件
        self.current_emails = []

    def create_widgets(self):
        """创建程序界面"""
        # 创建主选项卡
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)

        # 发送邮件标签页
        self.send_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.send_frame, text="发送邮件")
        self.create_send_tab()

        # 接收邮件标签页
        self.receive_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.receive_frame, text="接收邮件")
        self.create_receive_tab()

        # 配置标签页
        self.config_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.config_frame, text="配置")
        self.create_config_tab()

    def create_send_tab(self):
        """创建发送邮件标签页"""
        main_frame = ttk.Frame(self.send_frame, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 收件人输入框
        ttk.Label(main_frame, text="收件人:").grid(row=0, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.to_var, width=60).grid(row=0, column=1, columnspan=2, pady=5)

        # 抄送输入框
        ttk.Label(main_frame, text="抄送:").grid(row=1, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.cc_var, width=60).grid(row=1, column=1, columnspan=2, pady=5)

        # 密送输入框
        ttk.Label(main_frame, text="密送:").grid(row=2, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.bcc_var, width=60).grid(row=2, column=1, columnspan=2, pady=5)

        # 主题输入框
        ttk.Label(main_frame, text="主题:").grid(row=3, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.subject_var, width=60).grid(row=3, column=1, columnspan=2, pady=5)

        # HTML模式复选框
        ttk.Checkbutton(main_frame, text="HTML模式", variable=self.html_mode_var).grid(row=4, column=0, sticky=tk.W,
                                                                                     pady=5)

        # 内容输入框（带滚动条）
        ttk.Label(main_frame, text="内容:").grid(row=5, column=0, sticky=tk.NW, pady=5)
        self.content_text = scrolledtext.ScrolledText(main_frame, width=70, height=15)
        self.content_text.grid(row=5, column=1, columnspan=2, pady=5)

        # 附件列表
        ttk.Label(main_frame, text="附件:").grid(row=6, column=0, sticky=tk.W, pady=5)
        self.attach_listbox = tk.Listbox(main_frame, width=60, height=4)
        self.attach_listbox.grid(row=6, column=1, pady=5)

        # 附件操作按钮
        attach_btn_frame = ttk.Frame(main_frame)
        attach_btn_frame.grid(row=6, column=2, sticky=tk.NW, padx=5)
        ttk.Button(attach_btn_frame, text="添加", command=self.add_attachment).pack(fill=tk.X)
        ttk.Button(attach_btn_frame, text="删除", command=self.remove_attachment).pack(fill=tk.X)

        # 发送邮件按钮
        ttk.Button(main_frame, text="发送邮件", command=self.send_email).grid(row=7, column=1, pady=20)

    def create_receive_tab(self):
        """创建接收邮件标签页"""
        main_frame = ttk.Frame(self.receive_frame, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 搜索条件
        ttk.Label(main_frame, text="搜索条件:").grid(row=0, column=0, sticky=tk.W, pady=5)
        search_frame = ttk.Frame(main_frame)
        search_frame.grid(row=0, column=1, sticky=tk.W)
        ttk.Entry(search_frame, textvariable=self.search_criteria_var, width=40).pack(side=tk.LEFT)
        ttk.Button(search_frame, text="搜索", command=self.fetch_emails).pack(side=tk.LEFT, padx=5)

        # 邮件列表
        ttk.Label(main_frame, text="邮件列表:").grid(row=1, column=0, sticky=tk.NW, pady=5)
        self.email_listbox = tk.Listbox(main_frame, width=80, height=12)
        self.email_listbox.grid(row=1, column=1, pady=5, sticky=tk.NSEW)

        # 邮件内容显示区域（带滚动条）
        ttk.Label(main_frame, text="邮件内容:").grid(row=2, column=0, sticky=tk.NW, pady=5)
        self.email_content = scrolledtext.ScrolledText(main_frame, width=80, height=20)
        self.email_content.grid(row=2, column=1, pady=5, sticky=tk.NSEW)

        # 操作按钮
        btn_frame = ttk.Frame(main_frame)
        btn_frame.grid(row=3, column=1, pady=10)
        ttk.Button(btn_frame, text="获取邮件", command=self.fetch_emails).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="查看邮件", command=self.view_email).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="删除邮件", command=self.delete_email).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="保存附件", command=self.save_attachment).pack(side=tk.LEFT, padx=5)

        # 配置网格布局权重
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(1, weight=1)
        main_frame.rowconfigure(2, weight=2)

    def create_config_tab(self):
        """创建配置标签页"""
        main_frame = ttk.Frame(self.config_frame, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # SMTP配置
        ttk.Label(main_frame, text="SMTP服务器:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.smtp_server_entry = ttk.Entry(main_frame, width=40)
        self.smtp_server_entry.grid(row=0, column=1, pady=5)
        self.smtp_server_entry.insert(0, self.config.get_smtp_server())

        ttk.Label(main_frame, text="SMTP端口:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.smtp_port_entry = ttk.Entry(main_frame, width=40)
        self.smtp_port_entry.grid(row=1, column=1, pady=5)
        self.smtp_port_entry.insert(0, str(self.config.get_smtp_port()))

        # IMAP配置
        ttk.Label(main_frame, text="IMAP服务器:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.imap_server_entry = ttk.Entry(main_frame, width=40)
        self.imap_server_entry.grid(row=2, column=1, pady=5)
        self.imap_server_entry.insert(0, self.config.get_imap_server())

        ttk.Label(main_frame, text="IMAP端口:").grid(row=3, column=0, sticky=tk.W, pady=5)
        self.imap_port_entry = ttk.Entry(main_frame, width=40)
        self.imap_port_entry.grid(row=3, column=1, pady=5)
        self.imap_port_entry.insert(0, str(self.config.get_imap_port()))

        # POP3配置
        ttk.Label(main_frame, text="POP3服务器:").grid(row=4, column=0, sticky=tk.W, pady=5)
        self.pop3_server_entry = ttk.Entry(main_frame, width=40)
        self.pop3_server_entry.grid(row=4, column=1, pady=5)
        self.pop3_server_entry.insert(0, self.config.get_pop3_server())

        ttk.Label(main_frame, text="POP3端口:").grid(row=5, column=0, sticky=tk.W, pady=5)
        self.pop3_port_entry = ttk.Entry(main_frame, width=40)
        self.pop3_port_entry.grid(row=5, column=1, pady=5)
        self.pop3_port_entry.insert(0, str(self.config.get_pop3_port()))

        # 邮箱账号和密码
        ttk.Label(main_frame, text="邮箱地址:").grid(row=6, column=0, sticky=tk.W, pady=5)
        self.email_entry = ttk.Entry(main_frame, width=40)
        self.email_entry.grid(row=6, column=1, pady=5)
        self.email_entry.insert(0, self.config.get_email_address())

        ttk.Label(main_frame, text="密码/授权码:").grid(row=7, column=0, sticky=tk.W, pady=5)
        self.password_entry = ttk.Entry(main_frame, width=40, show="*")
        self.password_entry.grid(row=7, column=1, pady=5)
        self.password_entry.insert(0, self.config.get_password())

        # SSL/TLS选项
        self.ssl_var = tk.BooleanVar(value=self.config.get_use_ssl())
        ttk.Checkbutton(main_frame, text="使用SSL/TLS", variable=self.ssl_var).grid(row=8, column=1, sticky=tk.W, pady=5)

        # 保存按钮
        ttk.Button(main_frame, text="保存配置", command=self.save_config).grid(row=9, column=1, pady=20)

    def add_attachment(self):
        """添加附件"""
        files = filedialog.askopenfilenames(title="选择附件")
        if files:
            for file in files:
                self.attach_files.append(file)
                self.attach_listbox.insert(tk.END, os.path.basename(file))

    def remove_attachment(self):
        """删除选中的附件"""
        selection = self.attach_listbox.curselection()
        if selection:
            index = selection[0]
            self.attach_listbox.delete(index)
            del self.attach_files[index]

    def send_email(self):
        """发送邮件"""
        try:
            # 获取输入值
            to = self.to_var.get()
            subject = self.subject_var.get()
            content = self.content_text.get("1.0", tk.END).strip()
            cc = self.cc_var.get()
            bcc = self.bcc_var.get()
            html_mode = self.html_mode_var.get()
            attachments = self.attach_files

            # 验证必填字段
            if not all([to, subject]):
                messagebox.showwarning("警告", "收件人和主题是必填字段！")
                return

            # 发送邮件
            if html_mode:
                self.mail_sender.send_email(
                    to=to,
                    subject=subject,
                    content=None,
                    cc=cc,
                    bcc=bcc,
                    html_content=content,
                    attachments=attachments
                )
            else:
                self.mail_sender.send_email(
                    to=to,
                    subject=subject,
                    content=content,
                    cc=cc,
                    bcc=bcc,
                    html_content=None,
                    attachments=attachments
                )

            messagebox.showinfo("成功", "邮件发送成功！")

            # 清空表单
            self.to_var.set('')
            self.subject_var.set('')
            self.content_text.delete('1.0', tk.END)
            self.cc_var.set('')
            self.bcc_var.set('')
            self.attach_listbox.delete(0, tk.END)
            self.attach_files = []

        except Exception as e:
            messagebox.showerror("错误", f"发送邮件时出错:\n{str(e)}")

    def fetch_emails(self):
        """获取邮件列表"""
        try:
            # 清空邮件列表和内容显示
            self.email_listbox.delete(0, tk.END)
            self.email_content.delete(1.0, tk.END)
            self.current_emails = []

            # 获取邮件列表
            emails = self.mail_receiver.fetch_emails(
                limit=self.limit_var.get(),
                search_criteria=self.search_criteria_var.get()
            )

            if not emails:
                messagebox.showinfo("提示", "没有找到邮件")
                return

            self.current_emails = emails

            # 显示邮件列表
            for email_info in emails:
                display_text = f"{email_info['date']} | {email_info['from']} | {email_info['subject'][:50]}"
                self.email_listbox.insert(tk.END, display_text)

        except Exception as e:
            messagebox.showerror("错误", f"获取邮件时出错:\n{str(e)}")

    def view_email(self):
        """查看选中邮件的详细内容"""
        selection = self.email_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请选择一封邮件")
            return

        index = selection[0]
        if index >= len(self.current_emails):
            return

        email_info = self.current_emails[index]

        try:
            # 获取邮件内容
            content = self.mail_receiver.get_email_content(email_info)

            # 清空内容区域
            self.email_content.delete(1.0, tk.END)

            # 显示邮件基本信息
            self.email_content.insert(tk.END, f"发件人: {content['from']}\n")
            self.email_content.insert(tk.END, f"日期: {content['date']}\n")
            self.email_content.insert(tk.END, f"主题: {content['subject']}\n")
            self.email_content.insert(tk.END, "\n" + "=" * 80 + "\n\n")

            # 显示邮件正文
            if content['text']:
                self.email_content.insert(tk.END, "纯文本内容:\n")
                self.email_content.insert(tk.END, content['text'])
                self.email_content.insert(tk.END, "\n\n")

            if content['html']:
                self.email_content.insert(tk.END, "HTML内容:\n")
                # 去除HTML标签显示
                clean_html = re.sub('<[^<]+?>', '', content['html'])
                self.email_content.insert(tk.END, clean_html)
                self.email_content.insert(tk.END, "\n\n")

            # 显示附件信息
            if content['attachments']:
                self.email_content.insert(tk.END, "附件:\n")
                for attachment in content['attachments']:
                    self.email_content.insert(tk.END, f"- {attachment['filename']}\n")

        except Exception as e:
            messagebox.showerror("错误", f"查看邮件时出错:\n{str(e)}")

    def delete_email(self):
        """删除选中的邮件"""
        selection = self.email_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请选择一封邮件")
            return

        # 确认删除
        if not messagebox.askyesno("确认", "确定要删除这封邮件吗？"):
            return

        index = selection[0]
        if index >= len(self.current_emails):
            return

        email_info = self.current_emails[index]

        try:
            # 删除邮件
            if self.mail_receiver.delete_email(email_info):
                # 从列表中移除
                self.email_listbox.delete(index)
                del self.current_emails[index]
                messagebox.showinfo("成功", "邮件删除成功")
        except Exception as e:
            messagebox.showerror("错误", f"删除邮件时出错:\n{str(e)}")

    def save_attachment(self):
        """保存选中邮件的附件"""
        selection = self.email_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请选择一封邮件")
            return

        index = selection[0]
        if index >= len(self.current_emails):
            return

        email_info = self.current_emails[index]

        try:
            # 获取邮件内容
            content = self.mail_receiver.get_email_content(email_info)

            if not content['attachments']:
                messagebox.showinfo("提示", "这封邮件没有附件")
                return

            # 选择保存目录
            folder = filedialog.askdirectory(title="选择保存附件的目录")
            if not folder:
                return

            # 保存所有附件
            for attachment in content['attachments']:
                file_path = os.path.join(folder, attachment['filename'])
                with open(file_path, 'wb') as f:
                    f.write(attachment['data'])

            messagebox.showinfo("成功", f"成功保存 {len(content['attachments'])} 个附件")

        except Exception as e:
            messagebox.showerror("错误", f"保存附件时出错:\n{str(e)}")

    def save_config(self):
        """保存配置"""
        try:
            # 更新配置
            self.config.set_smtp_server(self.smtp_server_entry.get())
            self.config.set_smtp_port(self.smtp_port_entry.get())
            self.config.set_imap_server(self.imap_server_entry.get())
            self.config.set_imap_port(self.imap_port_entry.get())
            self.config.set_pop3_server(self.pop3_server_entry.get())
            self.config.set_pop3_port(self.pop3_port_entry.get())
            self.config.set_email_address(self.email_entry.get())
            self.config.set_password(self.password_entry.get())
            self.config.set_use_ssl(self.ssl_var.get())

            # 保存到文件
            if self.config.save_config():
                messagebox.showinfo("成功", "配置保存成功")

                # 重新初始化邮件发送和接收对象
                self.mail_sender = MailSender(self.config)
                self.mail_receiver = MailReceiver(self.config)

        except Exception as e:
            messagebox.showerror("错误", f"保存配置时出错:\n{str(e)}")


if __name__ == "__main__":
    root = tk.Tk()
    app = EmailApp(root)
    root.mainloop()
